;; search backward through current buffer for x urls, save them
;; dump list into a seperate buffer, bind enter key to browse-url-at-point
;; after selection (or quit), return to calling buffer at same position (save-excursion)?

(define-derived-mode erc-url fundamental-mode "Url Handler mode for ERC")

(defun get-last-urls (count)
  "Build a list of the <count> most recent urls in the buffer"
  (let ((urls '()))
    (save-excursion
      (while (or (< (length urls) count) (= point (point-min)))
        (re-search-backward "\\(http://.*\\)\\b")
        (add-to-list 'urls (match-string 0))))
    urls))

(defun handle-url-select ()
  "Open the URL, remap RET, close buffer - this doesn't completely work yet"
  (save-excursion
    (let ((url (thing-at-point 'url)))
      (browse-url url)
      (kill-buffer "*urls*"))))

(defun print-urls ()
  "Exposed function to open list of urls and allow opening"
  (interactive)
  (let ((urls (get-last-urls 5)))
    (switch-to-buffer "*urls*")
    (erc-url)
    (dolist (url urls) (insert (url-normalize-url url) "\n"))
    (goto-char 1)))

(define-key erc-url-map (kbd "RET") 'handle-url-select)
  

;; (defvar urlhandler-mode-hook nil)

;; (defvar urlhandler-mode-map
;;   (let ((urlhandler-mode-map (make-keymap)))
;;     (define-key urlhandler-mode-map "RET" 'handle-url-select))
;;   urlhandler-mode-mep)

;; (defun urlhandler-mode ()
;;   (interactive)
;;   (kill-all-local-variables)
;;   (use-local-map urlhandler-mode-map))

;; (setq major-mode 'urlhandler-mode)
;; (setq mode-name "UrlHandler")
;; (run-hooks 'urlhandler-mode)
;; (provide 'urlhandler-mode)
